﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using Itop.YHPC.Model;
using System.Collections.Generic;
using System.Text;
using Itop.YHPC.controller;

namespace Itop.YHPC.search
{
    public partial class Export1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            string option = Request.QueryString["option"];
            string text = Request.QueryString["text"];
            string sheetname = option.Split(',')[0];
            string type = option.Split(',')[1];
            if (id == null) {
                System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream, Encoding.UTF8);
                id = Server.UrlDecode( sr.ReadToEnd());//字符串格式id=id1,id2,
                sr.Close();
                if (id.Length > 3)
                    id = id.Substring(3);
                
            }
            int yhNo = GetTextNum(text);
            
            if (id != "")
            {
                string[] arr = id.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
                StringBuilder where = new StringBuilder();
                where.Append(" where 1<>1 ");
                foreach (string str in arr)
                    where.Append(" or id='"+str+"'");
                IList<yhpcMain> list = workflowController.GetMainList(where.ToString());
                if (type == "排查评估档案")
                {
                    FillData1(list, sheetname , "A", 0);
                    
                }
                else if (type == "治理验收档案")
                 {
                     FillData2(list, sheetname, "A", 0);
                 }
                    
                else
                    FillData(list, sheetname, "B",yhNo);
                //else
                    
            }
        }

        public void FillData(IList<yhpcMain> list,string sheetname,string type,int no)
        {
            int yhbh = no;
            string pathdic = "";
            if (Request.Path.Contains("yhpc")) pathdic = @"\yhpc";
            FileStream fs = new FileStream(Server.MapPath(pathdic+@"\search\Template\"+type+".xls"), FileMode.Open, FileAccess.Read);
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet;
            SortedDictionary<string,string> a_ht;
            if(type=="A")
                a_ht= GetAMapping();
            else 
                a_ht = GetBMapping();
            HSSFRow dataRow;
            int num = 0;
            foreach (yhpcMain main in list)
            {
                num++;
                sheet = templateWorkbook.CloneSheet(0);
                templateWorkbook.SetSheetName(0, "aa");
                dataRow = sheet.GetRow(1);
                dataRow.GetCell(0).SetCellValue(main.fxrq.Year.ToString()+"年度");
                for (int i = 0; i < main.GetType().GetProperties().Length; i++)
                {
                    string property = main.GetType().GetProperties()[i].Name;
                    if (a_ht.ContainsKey(property))
                    {
                        string cellvalue = main.GetType().GetProperty(property).GetValue(main, null).ToString();
                        if (main.GetType().GetProperties()[i].PropertyType.FullName == "System.DateTime")
                        { 
                            cellvalue = Convert.ToDateTime(cellvalue).ToString("yyyy-MM-dd");
                            if (cellvalue.StartsWith("1900-01-01"))
                                cellvalue = "";
                        }
                        dataRow = sheet.GetRow(GetRow(a_ht[property].ToString()));
                        if (type == "B" && property == "yhbh")
                            cellvalue ="长春供电公司"+ yhbh.ToString("00000000");
                        else if (type == "B" && property == "zlwcqc")
                        {
                            cellvalue = "预控措施：" + main.ykcs + "\n整改措施：" + main.zgcs + "\n治理完成情况：" + main.zlwcqc + "。";
                        }
                        
                        dataRow.GetCell(GetColumn(a_ht[property].ToString())).SetCellValue(cellvalue);
                    }
                }
                string temp = sheetname;
                if(sheetname=="一般事故隐患")
                    temp = "一般隐患";
                else if(sheetname=="重大事故隐患")
                    temp = "重大隐患";
                templateWorkbook.SetSheetName(num, temp + num.ToString());
                yhbh++;
            }
            templateWorkbook.RemoveSheetAt(0);
            string filename = sheetname+"档案表"+type+DateTime.Now.ToString("yyyy-MM-dd")+".xls";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();
            Response.BinaryWrite(WriteToStream(templateWorkbook).GetBuffer());
            Response.End();
        }
        //拆分为两个表后的方法
        public void FillData1(IList<yhpcMain> list, string sheetname, string type, int no)
        {
            int yhbh = no;
            string pathdic = "";
            if (Request.Path.Contains("yhpc")) pathdic = @"\yhpc";
            FileStream fs = new FileStream(Server.MapPath(pathdic + @"\search\Template\" + type + ".xls"), FileMode.Open, FileAccess.Read);
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet;
            SortedDictionary<string, string> a_ht=new SortedDictionary<string,string>();
           
                a_ht = GetAMapping1();
            //添加A
            HSSFRow dataRow;
            int num = 0;
            foreach (yhpcMain main in list)
            {
                num++;
                sheet = templateWorkbook.CloneSheet(0);
                templateWorkbook.SetSheetName(0, "aa");
                dataRow = sheet.GetRow(1);
                dataRow.GetCell(0).SetCellValue(main.fxrq.Year.ToString() + "年度");
                for (int i = 0; i < main.GetType().GetProperties().Length; i++)
                {
                    string property = main.GetType().GetProperties()[i].Name;
                    if (a_ht.ContainsKey(property))
                    {
                        string cellvalue = main.GetType().GetProperty(property).GetValue(main, null).ToString();
                        if (main.GetType().GetProperties()[i].PropertyType.FullName == "System.DateTime")
                        {
                            cellvalue = Convert.ToDateTime(cellvalue).ToString("yyyy-MM-dd");
                            if (cellvalue.StartsWith("1900-01-01"))
                                cellvalue = "";
                        }
                        dataRow = sheet.GetRow(GetRow(a_ht[property].ToString()));
                        if (type == "B" && property == "yhbh")
                            cellvalue = "长春供电公司" + yhbh.ToString("00000000");
                        else if (type == "B" && property == "zlwcqc")
                        {
                            cellvalue = "预控措施：" + main.ykcs + "\n整改措施：" + main.zgcs + "\n治理完成情况：" + main.zlwcqc + "。";
                        }

                        dataRow.GetCell(GetColumn(a_ht[property].ToString())).SetCellValue(cellvalue);
                    }
                }
                //insertpicture
                HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,2,255,2,6,7,6);
                anchor.AnchorType = 2;
                InsertPicture(templateWorkbook, sheet, main, "A", anchor);
                string temp = sheetname;
                if (sheetname == "一般事故隐患")
                    temp = "一般隐患";
                else if (sheetname == "重大事故隐患")
                    temp = "重大隐患";
                templateWorkbook.SetSheetName(num+1, temp + num.ToString());
                yhbh++;
            }
            templateWorkbook.RemoveSheetAt(0);
            templateWorkbook.RemoveSheetAt(0);
            string filename = "隐患排查评估档案"+ DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();
            Response.BinaryWrite(WriteToStream(templateWorkbook).GetBuffer());
            Response.End();
        }
        public void FillData2(IList<yhpcMain> list, string sheetname, string type, int no)
        {
            int yhbh = no;
            string pathdic = "";
            if (Request.Path.Contains("yhpc")) pathdic = @"\yhpc";
            FileStream fs = new FileStream(Server.MapPath(pathdic + @"\search\Template\" + type + ".xls"), FileMode.Open, FileAccess.Read);
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet;
            SortedDictionary<string, string> a_ht = new SortedDictionary<string, string>();

           
            //添加A
            HSSFRow dataRow;
            int num = 0;
           
            //添加B
            a_ht = GetCMapping();
            yhbh = no;          
            foreach (yhpcMain main in list)
            {
                num++;
                sheet = templateWorkbook.CloneSheet(1);
                templateWorkbook.SetSheetName(0, "bb");
                dataRow = sheet.GetRow(1);
                dataRow.GetCell(0).SetCellValue(main.fxrq.Year.ToString() + "年度");
                for (int i = 0; i < main.GetType().GetProperties().Length; i++)
                {
                    string property = main.GetType().GetProperties()[i].Name;
                    if (a_ht.ContainsKey(property))
                    {
                        string cellvalue = main.GetType().GetProperty(property).GetValue(main, null).ToString();
                        if (main.GetType().GetProperties()[i].PropertyType.FullName == "System.DateTime")
                        {
                            cellvalue = Convert.ToDateTime(cellvalue).ToString("yyyy-MM-dd");
                            if (cellvalue.StartsWith("1900-01-01"))
                                cellvalue = "";
                        }
                        dataRow = sheet.GetRow(GetRow(a_ht[property].ToString()));
                        if (type == "B" && property == "yhbh")
                            cellvalue = "长春供电公司" + yhbh.ToString("00000000");
                        else if (type == "B" && property == "zlwcqc")
                        {
                            cellvalue = "预控措施：" + main.ykcs + "\n整改措施：" + main.zgcs + "\n治理完成情况：" + main.zlwcqc + "。";
                        }

                        dataRow.GetCell(GetColumn(a_ht[property].ToString())).SetCellValue(cellvalue);
                    }
                }
                //
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 2, 255, 2, 12, 7, 12);
                anchor.AnchorType = 2;
                InsertPicture(templateWorkbook, sheet, main, "C", anchor);
                string temp = sheetname;
                if (sheetname == "一般事故隐患")
                    temp = "一般隐患";
                else if (sheetname == "重大事故隐患")
                    temp = "重大隐患";
                templateWorkbook.SetSheetName(num+1, temp + num.ToString());
                yhbh++;
            }

            templateWorkbook.RemoveSheetAt(0);
            templateWorkbook.RemoveSheetAt(0);
            string filename = "隐患治理验收档案" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();
            Response.BinaryWrite(WriteToStream(templateWorkbook).GetBuffer());
            Response.End();
        }
        MemoryStream WriteToStream(HSSFWorkbook templateWorkbook)
        {
            MemoryStream file = new MemoryStream();
            templateWorkbook.Write(file);
            return file;
        }
        public void InsertPicture( HSSFWorkbook wb,HSSFSheet sheet,yhpcMain main,string type,HSSFClientAnchor anchor)
        {
            string[] strExten = { "*.jpg", "*.bmp", "*.gif", "*.png" };
            string savePath = Server.MapPath("..\\Upload\\");
            string image ="";
            if (type=="A")
            {
                image = "image1" + main.id;
            }
            else if (type=="C")
            {
                image = "image3" + main.id;
            }
            string extys= ".jpg";
            bool imageflag = false;
            foreach (string strExtension in strExten)
            {

                               //if (!Directory.Exists(savePath))
                //{
                //    Directory.CreateDirectory(savePath);
                imageflag = false;
                    string pictype = image+ "_";
                    DirectoryInfo di = new DirectoryInfo(savePath);

                    FileInfo[] fi = di.GetFiles(strExtension);
                    
                    foreach (FileInfo f in fi)
                    {
                        if (f.Name.Contains(pictype))
                        {
                            imageflag = true;
                            savePath += f.Name;
                            extys = strExtension;
                            break;
                        }
                        
                    }
                    if (imageflag)
                    {
                        break;
                    }

              
            }
            // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray    
            // 读入图片1
            if (imageflag)
            {
                //System.IO.FileStream fs = new System.IO.FileStream(savePath, FileMode.Open, FileAccess.Read);
                //BinaryReader br = new BinaryReader(fs);
                //byte[] byteArrayOut = br.ReadBytes((int)fs.Length);
                //br.Close();
                //fs.Close();
              try
              {
                  byte[] byteArrayOut = File.ReadAllBytes(savePath);
                  //int pic = hssfworkbook.AddPicture(buff, HSSFWorkbook.PICTURE_TYPE_JPEG);
                  //HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 1, 1, 2, 2);
                  //anchor.AnchorType = 2;
                  //patriarch.CreatePicture(anchor, pic);

                  // 创建一个工作薄    


                  //HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 255, 255,
                  //        (short)6, 6, (short)10, 10);

                  // 插入图片1 
                  HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();

                  //switch (extys)
                  //{
                  //case "*.jpg" :
                  // patriarch.CreatePicture(anchor, wb.AddPicture(byteArrayOut
                  //        , HSSFWorkbook.PICTURE_TYPE_JPEG));
                  // break;
                  //    case"*.bmp":
                  // patriarch.CreatePicture(anchor, wb.AddPicture(byteArrayOut
                  //                    , HSSFWorkbook.);
                  // break;
                  //}

             HSSFPicture picture=  patriarch.CreatePicture(anchor, wb.AddPicture(byteArrayOut
                         , HSSFWorkbook.PICTURE_TYPE_JPEG));
         
              }
              catch (System.Exception ex)
              {
              	
              }
              

            }
            
           


        }
        public int GetRow(string str)
        {
            return int.Parse(str.Split('|')[0])-1;
        }

        public int GetColumn(string str)
        {
            return int.Parse(str.Split('|')[1])-1;
        }

        public int GetTextNum(string text)
        {
            if (string.IsNullOrEmpty(text))
                return 0;
            string rst=text;
            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] != '0')
                { rst = text.Substring(i); break; }
            }
            return int.Parse(rst);
        }

        public SortedDictionary<string, string> GetAMapping()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            ht["yhjt"] = "3|3";
            ht["yhly"] = "3|7";
            ht["yhbh"] = "4|3";
            ht["yhdw"] = "4|5";
            ht["yhzyfl"]="4|7";
            ht["yhfxr"]="5|3";
            ht["fxrdw"]="5|5";
            ht["fxrq"]="5|7";
            ht["fxyhnr"]="6|3";
            ht["knhg"]="7|3";
            ht["gsbm"]="7|7";
            ht["ypgdj"]="8|3";
            ht["ypgfzr"]="8|5";
            ht["ypgrq1"]="8|7";
            ht["ypgsh2"]="9|5";
            ht["ypgrq2"]="9|7";
            ht["ypgsh3"]="10|5";
            ht["ypgrq3"]="10|7";
            ht["pgdj"]="11|3";
            ht["pgfzr"]="11|5";
            ht["pgrq1"]="11|7";
            ht["pgsh2"]="12|5";
            ht["pgrq2"]="12|7";
            ht["pgsh3"]="13|5";
            ht["pgrq3"]="13|7";
            ht["pgsh4"]="14|5";
            ht["pgrq4"]="14|7";
            ht["ykcs"]="15|3";
            ht["zgcs"]="16|3";
            ht["zldw"]="17|3";
            ht["zlr"]="17|6";
            ht["zlrq1"]="18|4";
            ht["zlrq2"] = "18|6";
            ht["zlwcqc"]="19|3";
            ht["yssqdw"]="20|3";
            ht["yssqfzr"]="20|5";
            ht["yssqrq"]="20|7";
            ht["yszzdw"]="21|3";
            ht["ysyj"]="22|3";
            ht["ysjl"]="23|3";
            ht["yssfxc"]="23|7";
            ht["yszz"]="24|3";
            ht["ysrq"]="24|7";


            return ht;
        }
        //新的
        public SortedDictionary<string, string> GetAMapping1()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            ht["yhjt"] = "3|3";
            ht["yhly"] = "3|7";
            ht["yhbh"] = "4|3";
            ht["yhdw"] = "4|5";
            ht["yhzyfl"] = "4|7";
            ht["yhfxr"] = "5|3";
            ht["fxrdw"] = "5|5";
            ht["fxrq"] = "5|7";
            ht["fxyhnr"] = "6|3";
            ht["picture"] = "7|3";
            ht["knhg"] = "8|3";
            ht["gsbm"] = "8|7";
            ht["ypgdj"] = "9|3";
            ht["ypgfzr"] = "9|5";
            ht["ypgrq1"] = "9|7";
            ht["ypgsh2"] = "10|5";
            ht["ypgrq2"] = "10|7";
            ht["ypgsh3"] = "11|5";
            ht["ypgrq3"] = "11|7";
            ht["pgdj"] = "12|3";
            ht["pgfzr"] = "12|5";
            ht["pgrq1"] = "12|7";
            ht["pgsh2"] = "13|5";
            ht["pgrq2"] = "13|7";
            ht["pgsh3"] = "14|5";
            ht["pgrq3"] = "14|7";
            ht["pgsh4"] = "15|5";
            ht["pgrq4"] = "15|7";
           

            return ht;
        }
        public SortedDictionary<string, string> GetCMapping()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            ht["yhjt"] = "3|3";
            ht["yhly"] = "3|7";
            ht["yhbh"] = "4|3";
            ht["yhdw"] = "4|5";
            ht["yhzyfl"] = "4|7";
            ht["yhfxr"] = "5|3";
            ht["fxrdw"] = "5|5";
            ht["fxrq"] = "5|7";
            ht["fxyhnr"] = "6|3";
            ht["ypgdj"] = "7|3";
            ht["gsbm"] = "7|7";
            ht["ykcs"] = "8|3";
            ht["zgcs"] = "9|3";
            ht["zldw"] = "10|3";
            ht["zlr"] = "10|6";
            ht["zlrq1"] = "11|4";
            ht["zlrq2"] = "11|6";
            ht["zlwcqc"] = "12|3";
            ht["picture"] = "13|4";
            ht["yssqdw"] = "14|3";
            ht["yssqfzr"] = "14|5";
            ht["yssqrq"] = "14|7";
            ht["yszzdw"] = "15|3";
            ht["ysyj"] = "16|3";
            ht["ysjl"] = "17|3";
            ht["yssfxc"] = "17|7";
            ht["yszz"] = "18|3";
            ht["ysrq"] = "18|7";

            
            return ht;
        }

        public SortedDictionary<string, string> GetBMapping()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            ht["yhjt"] = "3|3";
            ht["yhly"] = "3|7";
            ht["yhbh"] = "4|3";
            ht["yhdw"] = "4|5";
            ht["yhzyfl"] = "4|7";
            ht["yhfxr"] = "5|3";
            ht["fxrdw"] = "5|5";
            ht["fxrq"] = "5|7";
            ht["fxyhnr"] = "6|3";
            ht["knhg"] = "7|3";
            ht["gsbm"] = "7|7";
            ht["ypgdj"] = "8|3";
            ht["ypgfzr"] = "8|5";
            ht["ypgrq1"] = "8|7";
            ht["ypgsh3"] = "9|5";
            ht["ypgrq3"] = "9|7";
            ht["pgdj"] = "10|3";
            ht["pgfzr"] = "10|5";
            ht["pgrq1"] = "10|7";
            ht["pgsh4"] = "11|5";
            ht["pgrq4"] = "11|7";
            ht["zldw"] = "12|3";
            ht["zlr"] = "12|6";
            ht["zlrq1"] = "13|4";
            ht["zlrq2"] = "13|6";
            ht["zlwcqc"] = "14|3";
            ht["yssqdw"] = "15|3";
            ht["yssqfzr"] = "15|5";
            ht["yssqrq"] = "15|7";
            ht["yszzdw"] = "16|3";
            ht["ysyj"] = "17|3";
            ht["ysjl"] = "18|3";
            ht["yssfxc"] = "18|7";
            ht["yszz"] = "19|3";
            ht["ysrq"] = "19|7";


            return ht;
        }
    }
}
